<?php
$http = new Swoole\Http\Server("0.0.0.0", 94);
$conf = '';
include 'db.php';
$http->set([
    'reload_async' => true
]);
$http->on('request', function ($request, $response) use ($conf) {
    // 请求头处理跨域
    $response->header('Content-Type', 'application/json; charset=utf-8');
    $response->header('access-control-allow-credentials', 'true');
    $response->header('access-control-allow-methods', 'GET,HEAD,POST,OPTIONS');
    $response->header('access-control-allow-headers', 'content-type,Authorization');
    $response->header('Access-Control-Allow-Private-Network', 'true');
    $origin = empty($request->header['origin']) ? '*' : $request->header['origin'];
    $response->header('access-control-allow-origin', $origin);
    $request_method = empty($request->server['request_method']) ? '' : $request->server['request_method'];
    if ($request_method == "OPTIONS") {
        $response->status(200);
        $response->end();
        return;
    }
    if ($request->server['request_uri']  != "/report") {
        $response->status(400);
        $response->end(json_encode(['code' => '0', 'message' => 'error uri', 'data'=>[]]));
        return;
    }
    $ip = realIP($request);
    $logData = [
        'method' => $request_method,
        'time' => date('Y-m-d H:i:s'),
        'ip' => $ip,
        'query' => $request->server['query_string'] ?? '',
    ];

    logfile($logData);
    $data = $request->get['data'] ?? null;
    // 预定义有效的 counter 列表
    $valid_counters = ['chat', 'online', 'load'];
    // 解析 URL 参数
    $counter = $request->get['counter'] ?? null;
    $data = $request->server['query_string'] ?? '';
    if ($counter == 'load') $data = $data.'&ip='.$ip;
    // 检查 counter 是否有效
    if (in_array($counter, $valid_counters, true) && $data !== null) {
        $redis = new Redis();
        $redis->connect($conf['redis']['host'], $conf['redis']['port']);
        $redis->auth($conf['redis']['pass']);  // 替换为您的 Redis 密码

        // 将 data 参数的值放入 Redis 队列
        $res = $redis->lpush('report_'.$counter, $data);
        // 关闭 Redis 连接
        $redis->close();
        $response->end(json_encode(['code' => '1', 'message' => 'success', 'data'=>[]]));
    } else {
        $response->status(400);
        $response->end(json_encode(['code' => '0', 'message' => 'Invalid or missing counter/data parameter', 'data'=>[]]));
    }
});
$http->on('WorkerStop', function ($server, $workerId) {

});
$http->on('WorkerExit', function ($server, $worker_id) use ($conf) {

});
$http->start();

function logfile($logData)
{
    $logFile = FILE_PATH.date('Ymd').'.log';
    file_put_contents($logFile, json_encode($logData) . PHP_EOL, FILE_APPEND);
}

function realIP($request)
{
    $realIp = $request->header['x-real-ip'] ?? '';
    if (empty($realIp)) {
        // 如果没有X-Real-IP，尝试使用X-Forwarded-For
        $xff = $request->header['x-forwarded-for'] ?? '';
        $ips = explode(',', $xff);
        $realIp = trim($ips[0]);
    }

    // 确保验证IP的有效性
    if (!filter_var($realIp, FILTER_VALIDATE_IP)) {
        // 如果不是有效的IP地址，则可能需要进一步处理或记录错误
        $realIp = $request->server['remote_addr'];
    }
    return $realIp;
}
